<template>
    <Header></Header>
    <div style="width: 100%;display: flex;justify-content: center;background-color: rgba(247, 247, 247, 1);padding-top: 50px;padding-bottom:120px;">
        <!--        {{data.play_auth}}-->
        <div style="width: 1200px">
            <!--        视频播放{{subject_id}}{{subject_name}}-->
            <div class="play-header">
                <el-icon @click="leftContentIsShow" style="margin-left:10px;color: white;cursor: pointer" :size="20"><Expand /></el-icon>
                <span class="title">目录</span>
                <span class="title">{{data.activeName}}</span>
            </div>
            <div class="player">
                <div v-if="data.leftContent" class="play-left">
                    <div style="padding: 20px" v-for="item in data.videoChapter">
                        <div>
                            <div class="title">{{item.name}}</div>
                            <div v-if="item.courseVideos.length">
                                <div :class="children.id == data.id ? 'activeVideoLeft':''" @click="toVideo(children)" class="videoName" v-for="children in item.courseVideos">
                                    {{children.name}}
                                </div>
                            </div>
                            <div v-if="item.subsections.length">
                                <div v-for="son in item.subsections">
                                    <div class="subjectName">{{son.name}}</div>
                                    <div v-if="son.courseVideos.length">
                                        <div @click="toVideo(children)"  :class="children.id == data.id ? 'activeVideoLeft':''" class="videoName" v-for="children in son.courseVideos">
                                            {{children.name}}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <Player
                        @ready="onReady"
                        :vid="data.v_id"
                        :play_auth="data.play_auth"
                        ref="playerRef"
                        @playing="videoPlay"
                        @pause="videoPause"
                        :wh_ratio="1920/1080">
                </Player>
            </div>
            <div class="video-body">
                <el-row justify="space-between">
                    <el-col :span="17">
<!--                        <span>123{{data.routerName}}</span>-->
                        <el-breadcrumb :separator-icon="'ArrowRightBold'">
                            <el-breadcrumb-item class="link" @click="$router.push({name:'index'})">首页</el-breadcrumb-item>
                            <el-breadcrumb-item class="link" @click="$router.push({name:'MyCourseAccount'})">我的课程</el-breadcrumb-item>
                            <!--                            <el-breadcrumb-item v-if="data.routerName == 'MyCourseAccount'" class="link" @click="$router.push({name:'MyCourse'})">我的网课</el-breadcrumb-item>-->
                            <!--                            <el-breadcrumb-item v-if="data.routerName == 'MoreCourse'" class="link" @click="$router.push({name:'MoreCourse',params: {activeName:'我的课程'}})">我的课程</el-breadcrumb-item>-->
                            <el-breadcrumb-item>{{subject_name}}</el-breadcrumb-item>
                            <el-breadcrumb-item style="display:inline-block;width: 450px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">{{data.activeName}}</el-breadcrumb-item>
                        </el-breadcrumb>
                        <div style="display: flex;justify-content: space-between;align-items: center;padding: 20px 0px">
                            <span>{{data.activeName}}</span>
                            <div>
                              <el-button  v-if="data.videoFiles.length" @click="toPdf(data.videoFiles[0])">
                                <el-icon class="el-icon--left"><View /></el-icon>
                                课件
                              </el-button>
                              <el-button @click="add_like" :type="data.isCollect?'primary':''">
                                <el-icon class="el-icon--left"><Star /></el-icon>
                                收藏
                              </el-button>
                            </div>
                        </div>
                        <div>
                            <el-card>
<!--                                {{data.chapterID}}-->
                                <el-collapse v-for="item in data.videoChapter" v-model="data.chapterID" accordion>
                                    <!--                                    {{item.id}}{{data.chapterID}}-->
                                    <el-collapse-item :title="item.name" :name="item.id">
                                        <div class="course-title" v-if="item.courseVideos.length" v-for="children in item.courseVideos">
                                            <div class="course-item" :class="children.id == data.id ? 'activeVideo':''" @click="toVideo(children)">
                                                <!--                                                {{children.chapterID}}{{$route.params.vid}}-->
                                              <div style="width:100%;display:flex; align-items: center;padding: 10px 0px">
                                                <el-icon :color="children.id == data.id ? '#0369a1' :''" style="margin-right: 20px" :size="25"><VideoCamera /></el-icon>
                                                <div style="display: flex;flex-direction: column">
                                                  <div><span class="name">{{children.name}}</span></div>
                                                  <div>
                                                    <div class="time" style="margin-right:20px;">
                                                      <span style="margin-right: 10px">已学习时长：{{proxy.$filters.timeFormat(children.watchTime)}}</span>
                                                      <span>视频时长：{{proxy.$filters.timeFormat(children.duration)}}</span>
                                                    </div>
                                                  </div>
                                                </div>
                                              </div>
                                            </div>
                                        </div>
                                        <el-collapse v-else-if="item.subsections.length" v-model="data.activeSubject" v-for="children in item.subsections" accordion>
                                            <el-collapse-item style="margin-left: 20px" :title="children.name" :name="children.id">
                                                <!--                                                {{children}}-->
                                                <div class="course-title" v-if="children.courseVideos.length" v-for="son in children.courseVideos">
                                                    <div class="course-item" :class="son.id == data.id ? 'activeVideo':''" @click="toVideo(son)">
                                                        <!--                                                        {{son.chapterID}}{{$route.params.vid}}-->
                                                      <div style="width:100%;display:flex; align-items: center;padding: 10px 0px">
                                                        <el-icon :color="son.id == data.id ? '#0369a1' :''" style="margin-right: 20px" :size="25"><VideoCamera /></el-icon>
                                                        <div style="display: flex;flex-direction: column">
                                                          <div><span class="name">{{son.name}}</span></div>
                                                          <div>
                                                            <div class="time" style="margin-right:20px;">
                                                              <span style="margin-right: 10px">观看时长：{{proxy.$filters.timeFormat(son.watchTime)}}</span>
                                                              <span>视频时长：{{proxy.$filters.timeFormat(son.duration)}}</span>
                                                            </div>
                                                          </div>
                                                        </div>
                                                      </div>
                                                    </div>
                                                </div>
                                            </el-collapse-item>
                                        </el-collapse>
                                    </el-collapse-item>
                                </el-collapse>
                            </el-card>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <el-card>
                          <el-row>
                            <el-col :span="24">
                              <div style="display: flex;align-items: center">
                                <el-avatar :size="50" :src="data.admin.avatarPic || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"/>
                                <div style="margin-left: 20px" @click="test">讲师：{{ data.admin.name }}</div>
                              </div>
                            </el-col>
                            <el-col :span="24">
                              <div>
                                <!--                                        {{data.location}}&#45;&#45;{{TotalSecondRef}}-->
                                <div style="font-size: 14px;margin-top: 10px" v-if="data.admin.describe">简介：{{ data.admin.describe }}</div>
                              </div>
                            </el-col>
                          </el-row>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
        </div>
    </div>
    <staticFooter></staticFooter>
</template>

<script>
    import staticFooter from "../../../components/staticFooter";
    import Header from "../../../components/Header";
    import Cookies from 'js-cookie'
    import {set_bull_screen} from "../../../components/Player/js/player_components";
    import Player from "../../../components/Player/Player";
    import {
      reactive,
      toRefs,
      ref,
      watchEffect,
      onMounted,
      onBeforeUnmount,
      getCurrentInstance,
      computed,
      nextTick, watch
    } from 'vue'
    import {useRoute, useRouter} from "vue-router";
    import {meCollectORCancel, recentVideoList, videoAuthVideo, videoChapter, videoTimer} from "../../../api/api";
    import {ElMessage} from "element-plus";
    export default {
        name: "index",
        setup(){
            // beforeRouteEnter((to,form,next)=>{
            //     //to 到哪里去
            //     //form 从哪里来
            //     next( vm => {
            //         console.log('form',form)
            //         if(form.path == '/'){
            //             vm.data.routerName = vm.data.routerName
            //         }else{
            //             vm.data.routerName = form.name;
            //         }
            //     })
            // })
            const { proxy } = getCurrentInstance()
            let route = useRoute();
            let router = useRouter();
            let player = null;
            const playerRef = ref(null);
            let data = reactive({
                add_like_state:false,
                routerName:"MoreCourse",
                id:null,
                v_id:'',
                play_auth:'',
                activeName:'',
                videoChapter:[],
                admin:{},
                leftContent:false,
                chapterID:'',
                activeTotalTime:null,
                activeSubject:null,
                location:null,
                isCollect:false,
                totalSecond:0,
                videoFiles:[]
            })

            const toPdf = (videoFile) =>{
              const href = router.resolve({ //使用resolve
                name:'pdfContainer',    //这里是跳转页面的name
                params:{pdf:videoFile.url}
              })
              window.open(href.href,"_blank")
            }



            let {subject_id,subject_name,id,chapterID} = route.params;
            console.log('route',route)
            let setLocation = (location) =>{
                playerRef.value.player.seek(location)
            }

            let getVideoAuthVideo = (vid) =>{
                videoAuthVideo({id:vid}).then(res =>{
                    console.log('视频详情',res);
                    data.id = vid;
                    data.v_id = res.data.vid
                    data.play_auth = res.data.playAuth;
                    data.admin = res.data.admin
                    data.activeTotalTime = res.data.duration
                    data.isCollect = res.data.isCollect;
                    data.location = res.data.location;
                    data.videoFiles = res.data.videoFiles;
                    set_bull_screen(localStorage.getItem('nickname'))
                })
            }

            //播放器加载完成
            let onReady = () =>{
                console.log('播放时间',data.location,playerRef.value.player)
                playerRef.value.player.seek(data.location);
                console.log('播放器初始化')
            }

            //当前播放状态
            let activeState = (activeId) =>{
                for (let item of data.videoChapter){
                    if(item.courseVideos && item.courseVideos.length){
                        for (let children of item.courseVideos){
                            if(children.id == activeId){
                                console.log('当前属于章节下的',children);
                                data.chapterID = children.chapterID;
                                data.activeName = children.name;
                            }
                        }
                    }else{
                        for (let item2 of item.subsections){
                            if(item2.courseVideos && item2.courseVideos.length){
                                for (let children of item2.courseVideos){
                                    if(children.id == activeId){
                                        console.log('当前属于章节及小节下的',item2,children);
                                        data.activeSubject = item2.id;
                                        data.chapterID = item2.chapterID;
                                        data.activeName = children.name
                                    }
                                }
                            }
                        }
                    }
                }
            }

            let getRecentVideoList = () =>{
                let courseId = localStorage.getItem('activeCourse');
                console.log('当前课程id',courseId);
                recentVideoList({courseID:courseId}).then(res =>{
                    console.log('最近在学视频列表',res)
                    if(res.data.rows.length){
                        let courseHistory = res.data.rows.filter(item => item.subjectID == id);
                        console.log(courseHistory)
                        if(courseHistory.length){
                            let activeId = courseHistory[0].id;
                            data.id = courseHistory[0].id;
                            data.location = courseHistory[0].location;
                            data.activeName = courseHistory[0].name;
                            activeState(activeId);
                            getVideoAuthVideo(activeId);
                        }else{
                            let activeCourse = data.videoChapter[0].subsections && data.videoChapter[0].subsections.length ? data.videoChapter[0].subsections[0].courseVideos[0] : data.videoChapter[0].courseVideos[0]
                            let activeId = activeCourse.id;
                            console.log('activeId',activeId)
                            data.id = activeCourse.id;
                            data.location = 0;
                            data.activeName = activeCourse.name;
                            activeState(activeId);
                            getVideoAuthVideo(activeId);
                        }
                    }else{
                        let activeId = data.videoChapter[0].subsections.length ? data.videoChapter[0].subsections[0].courseVideos[0].id : data.videoChapter[0].courseVideos[0].id
                        data.id = activeId;
                        console.log('activeId',activeId)
                        activeState(activeId);
                        getVideoAuthVideo(activeId);
                    }
                })
            }

            let test = () =>{
                // console.log('123')
                // playerRef.value.player.on('playing',(event) => {
                //     console.log('event',event)
                // })

                // let parasm = {
                //     videoID:data.id,
                //     minute:playerRef.value.player.getCurrentTime(),
                //     totalSecond:Number(data.activeTotalTime)
                // }
                // Cookies.set('test','1222222223')
                //
                // videoTimer(parasm).then(res =>{
                //     console.log('记录成功',res);
                // })
            }

            let getVideoChapter = (chapter_id) =>{
                videoChapter({subjectID:chapter_id}).then(res =>{
                    console.log('视频列表',res)
                    data.videoChapter = res.data.chapters;
                    if(chapterID != 0){
                        getVideoAuthVideo(id);
                        activeState(id);
                    }else{
                        getRecentVideoList();
                    }
                })
            }

            let chapter_id = chapterID != 0 ? chapterID : id

            getVideoChapter(chapter_id);

            let leftContentIsShow = () =>{
                data.leftContent = !data.leftContent
            }

            let toVideo = (item) =>{
                getVideoAuthVideo(item.id);
                activeState(item.id)
                data.location = null;
                // router.push({name:'VideoPlayer',params:{subject_id:subject_id,subject_name:subject_name,vid:item.id,activeName:item.name}})
            }

            let add_like = () =>{
                data.isCollect = !data.isCollect
                meCollectORCancel({courseVideoID:data.id}).then(res =>{
                    console.log('视频收藏',res)
                    ElMessage({type:'success',message:res.data.message})
                })
            }

            //播放器暂停
            let videoPause = () =>{
                console.log('播放器暂停')
                clearInterval(timer.value);
            }

            //播放器播放中
            let videoPlay = () =>{
                clearInterval(timer.value);
                console.log('正在播放---',Math.random())
                createInterval()
            }
            let timer = ref(null);
            let TotalSecondRef = ref(0);
            let createInterval = () =>{
                timer.value = setInterval(() =>{
                    // console.log(playerRef.value.player.getStatus())
                    if(playerRef.value.player && playerRef.value.player.getStatus() == 'playing'){
                        TotalSecondRef.value++;
                    }else{
                        // clearInterval(timer.value);
                    }
                },1000)
            }

            let videoTimerFun = () =>{
                console.log('player',data.id);
                console.log(playerRef.value.player.getCurrentTime());
                console.log(TotalSecondRef.value)
                let parasm = {
                    videoID:data.id,
                    minute:playerRef.value.player.getCurrentTime(),
                    totalSecond:Number(TotalSecondRef.value)
                }
                // Cookies.set('test','1222222223')

                videoTimer(parasm).then(res =>{
                    console.log('记录成功',res);
                })
                window.removeEventListener('beforeunload',() =>{

                });
            }
            // e141687531aa4c5682143f842e1315cd
            // e141687531aa4c5682143f842e1315cd
            onBeforeUnmount(() =>{
                console.log('组件销毁-------')
                videoTimerFun();
                clearInterval(timer.value);
            })

            //
            window.addEventListener('beforeunload', videoTimerFun);
            return{
                toPdf,
                videoPause,
                TotalSecondRef,
                videoPlay,
                proxy,
                onReady,
                test,
                playerRef,
                add_like,
                leftContentIsShow,
                toVideo,
                data,
                player,
                subject_id,
                subject_name,
                // activeName
            }
        },
        components:{
            Player,
            Header,
            staticFooter
        }
    }
</script>

<style scoped>
    .link{
        cursor: pointer;
    }
    .link :hover{
        color: #409eff !important;
    }
    .player{
        position: relative;
    }
    .player .title{
        color: rgba(204, 204, 204, 1);
        font-size: 14px;
        font-weight: 400;
    }

    .player .subjectName{
        color: rgba(148, 150, 153, 1);
        font-size: 12px;
        font-weight: 400;
        margin-top: 20px;
    }

    .player .videoName{
        color: rgba(148, 150, 153, 1);
        font-size: 12px;
        font-weight: 400;
        margin-left: 10px;
        margin-bottom: 5px;
        cursor: pointer;
    }
    .player .videoName:hover{
        color: yellow;
    }
    .activeVideoLeft{
        color: yellow !important;
    }
    .play-header{
        height: 55px;
        width: 100%;
        background-color: #1C1F21;
        display: flex;
        align-items: center;
    }
    .play-header .title{
        margin-left: 10px;
        color: rgba(148, 150, 153, 1);
    }
    .play-left{
        position: absolute;
        width: 20%;
        height: calc(100% - 44px);
        background: rgba(51, 51, 51, 1);
        left: 0px;
        top: 0px;
        z-index: 2;
        overflow: scroll;
        max-height: calc(100% - 44px);
        overflow-x: hidden;
    }
    .play-left::-webkit-scrollbar {
        /*滚动条整体样式*/
        width : 10px;  /*高宽分别对应横竖滚动条的尺寸*/
        height: 1px;
    }
    .play-left::-webkit-scrollbar-thumb {
        /*滚动条里面小方块*/
        border-radius: 10px;
        box-shadow   : inset 0 0 5px rgba(0, 0, 0, 0.2);
        background   : #535353;
    }
    .play-left::-webkit-scrollbar-track {
        /*滚动条里面轨道*/
        box-shadow   : inset 0 0 5px rgba(0, 0, 0, 0.2);
        border-radius: 10px;
        background   : #ededed;
    }
    .course-item .time{
        font-size: 12px;
        color: rgba(153, 153, 153, 1);
    }
    .course-item .content{
        width: 100%;
        margin-left: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .course-item{
        display: flex;
        align-items: center;
        justify-content: space-between;
        line-height: 20px;
        margin-bottom: 5px;
        border-radius: 5px;
        margin-left: 10px;
        cursor: pointer;
        padding: 0 20px;
    }
    .course-item:hover{
        background-color: rgba(220,220,220,1);
    }
    .video-body{
        margin: 20px 0px;
        width: 1200px;
    }
    .activeVideo{
        background: #e0f2fe;
    }
</style>
